package com.weimi.phh.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by eddie on 15/8/28.
 */
public class DownloadImgUtils {

    private static ByteArrayOutputStream outputStream;

    public static Bitmap loadImageFromUrl(String path) throws Exception {

        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5*1000);
        conn.setRequestMethod("GET");
        InputStream inputStream = conn.getInputStream();
        if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
            outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1){
                outputStream.write(buffer,0,len);
            }

            byte[] imageArray = outputStream.toByteArray();
            return BitmapFactory.decodeByteArray(imageArray, 0, imageArray.length);
        }
        outputStream.close();
        inputStream.close();
        return null;
    }
}
